<template>
  <div class="dialog">
    <el-dialog
      title="生长数据模型配置"
      :visible.sync="showDialog"
      width="50%"
      @close="close"
    >
      <el-form :model="formDataM">
        <el-row style="padding: 10px">
          <el-col :span="12">
            <el-form-item label="批次名称:">
              <el-select
                v-model="formDataM.batchCodeNo"
                placeholder="请选择批次"
                style="width: 100%"
                clearable
                filterable
              >
                <el-option
                  v-for="(item, index) in batchList"
                  :key="index"
                  :label="item.batchName"
                  :value="item.batchCode"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="数据模型:">
              <el-select
                v-model="formDataM.growthModelId"
                placeholder="请选择数据模型"
                style="width: 100%"
                clearable
                filterable
                @change="changeModel"
              >
                <el-option
                  v-for="(item, index) in modelList"
                  :key="index"
                  :label="item.modelName"
                  :value="item.growthModelId"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="formDataM.varietiesEnvironmentStageList">
          <div
            v-for="(item, index) in formDataM.varietiesEnvironmentStageList"
            :key="index"
            class="growth-model"
          >
            <div class="growth-model-info">
              <el-row>
                <el-col :span="24">
                  <el-form-item label="生长周期:">
                    <el-select
                      v-model="item.growthPhaseId"
                      style="width: 100%"
                      placeholder="请选择生长周期"
                      clearable
                      filterable
                    >
                      <el-option
                        v-for="kit in growthPhaseIdList"
                        :key="kit.growthPhaseId"
                        :label="kit.phaseName"
                        :value="kit.growthPhaseId"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <div
                v-for="(key, indexA) in item.varietiesEnvironmentStageDataList"
                :key="indexA + 'hang'"
              >
                <el-row class="input-hang">
                  <el-col :span="10">
                    <el-form-item
                      label="数据类型:"
                      :prop="`varietiesEnvironmentStageList[${index}].varietiesEnvironmentStageDataList[${indexA}].dataTypeId`"
                      :rules="{
                        required: true,
                        message: '请选择数据项',
                        trigger: ['blur', 'change'],
                      }"
                    >
                      <el-select
                        v-model="key.dataTypeId"
                        placeholder="请选择数据项"
                        style="width: 100%"
                        filterable
                        clearable
                        @change="changeData($event, indexA, index)"
                      >
                        <el-option
                          v-for="kit in dataTypeList"
                          :key="kit.dataTypeId"
                          :label="kit.dataTypeName"
                          :value="kit.dataTypeId"
                        />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="7">
                    <el-form-item
                      label="上限:"
                      :prop="`varietiesEnvironmentStageList[${index}].varietiesEnvironmentStageDataList[${indexA}].upperValue`"
                      :rules="{
                        required: true,
                        message: '请输入上限',
                        trigger: ['blur', 'change'],
                      }"
                    >
                      <el-input
                        v-model="key.upperValue"
                        placeholder="请输入上限"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="7">
                    <el-form-item
                      label="下限:"
                      :prop="`varietiesEnvironmentStageList[${index}].varietiesEnvironmentStageDataList[${indexA}].lowerValue`"
                      :rules="{
                        required: true,
                        message: '请输入下限',
                        trigger: ['blur', 'change'],
                      }"
                    >
                      <el-input
                        v-model="key.lowerValue"
                        placeholder="请输入下限"
                      />
                    </el-form-item>
                  </el-col>
                  <img
                    v-if="item.varietiesEnvironmentStageDataList.length > 1"
                    src="~@/assets/conservation-model/model-data-del.png"
                    alt=""
                    class="btns"
                    @click="delModel(index, indexA)"
                  />
                  <img
                    v-if="
                      item.varietiesEnvironmentStageDataList.length ===
                        indexA + 1
                    "
                    src="~@/assets/conservation-model/model-data-add.png"
                    alt=""
                    class="btns"
                    @click="addModel(index, indexA)"
                  />
                </el-row>
              </div>
            </div>
          </div>
        </el-row>
      </el-form>
      <div class="submit-box">
        <el-button type="primary" class="submit" @click="onSubmit">
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import configurationApi from "@/api/digital-production/conservation-model/configuration";
import modeldataApi from "@/api/digital-production/conservation-model/model-data";

export default {
  name: "",
  components: {},
  props: {
    show: {
      type: Boolean,
      default: false
    },
    batchList: {
      type: Array,
      default: () => {
        return [];
      }
    },
    batchCode: {
      type: String,
      default: ""
    },
    plantingTypeId: {
      type: [String, Number],
      default: ""
    }
  },
  data() {
    return {
      showDialog: this.show,
      formDataM: {
        batchCodeNo: "",
        growthModelId: "",
        varietiesEnvironmentStageList: []
      },
      modelList: [],
      dataTypeList: [],
      growthPhaseIdList: [],
      isEidt: false,
      varietiesEnvironmentId: ""
    };
  },
  watch: {
    show(v) {
      this.showDialog = v;
      if (v === true) {
        this.queryModelInfo();
        this.queryDataType();
        this.queryByBatchCodeNo();
        this.formDataM.batchCodeNo = this.batchCode;
      }
    },
    plantingTypeId() {
      this.queryEditGrowthByvariety();
    }
  },
  created() {},
  mounted() {},
  methods: {
    // 查询已绑定的记录
    queryByBatchCodeNo() {
      configurationApi
        .queryByBatchCodeNo({
          batchCodeNo: this.batchCode
        })
        .then((res) => {
          if (res.code === 1) {
            let data = res.data || {};
            if (data) {
              if (data.varietiesEnvironmentId) {
                this.isEidt = true;
                this.formDataM = data;
                this.varietiesEnvironmentId = data.varietiesEnvironmentId;
              }
            }
          } else {
            this.$message.error(res.msg);
          }
        });
    },
    // 查询相关数据项
    queryDataType() {
      modeldataApi
        .queryDataType({
          organizationId: parseInt(sessionStorage.getItem("organizationId"))
        })
        .then((res) => {
          if (res.code === 1) {
            let data = res.data || [];
            this.dataTypeList = data;
          } else {
            this.$message.error(res.msg);
          }
        });
    },
    onSubmit() {
      this.formDataM.organizationId = sessionStorage.getItem("organizationId");
      // this.formDataM.batchCodeNo = this.batchCode;
      if (this.formDataM.growthModelId) {
        delete this.formDataM.growthModelId;
      }
      if (this.isEidt) {
        this.formDataM.varietiesEnvironmentId = this.varietiesEnvironmentId;
        this.loading = true;
        configurationApi.editVarieties(this.formDataM).then((res) => {
          this.loading = false;
          if (res.code === 1) {
            this.$message.success(res.msg);
            this.close();
          } else {
            this.$message.error(res.msg);
          }
        });
      } else {
        this.loading = true;
        configurationApi.addVarieties(this.formDataM).then((res) => {
          this.loading = false;
          if (res.code === 1) {
            this.$message.success(res.msg);
            this.close();
          } else {
            this.$message.error(res.msg);
          }
        });
      }
    },

    // 查询模板
    queryModelInfo() {
      let params = {
        organizationId: parseInt(sessionStorage.getItem("organizationId")),
        plantingTypeId: this.plantingTypeId
      };
      modeldataApi.queryByOrganizationIdAndType(params).then((res) => {
        if (res.code === 1) {
          let data = res.data || [];
          this.modelList = data;
        } else {
          this.$message.error(res.msg);
        }
      });
    },
    // 改变模板自动填充
    changeModel() {
      if (this.formDataM.growthModelId) {
        this.query(this.formDataM.growthModelId);
      } else {
        this.formDataM = {
          batchCodeNo: "",
          growthModelId: "",
          varietiesEnvironmentStageList: [
            {
              growthPhaseId: "",
              growthPhaseName: "",
              varietiesEnvironmentStageDataList: [
                {
                  dataTypeId: "",
                  dataTypeName: "",
                  upperValue: "",
                  lowerValue: ""
                }
              ]
            }
          ]
        };
      }
    },
    // 查询模板详情
    query(data) {
      modeldataApi
        .query({
          growthModelId: data
        })
        .then((res) => {
          if (res.code === 1) {
            let data = res.data || {};
            if (data) {
              // this.formDataM.plantingTypeName = data.plantingTypeName;
              let varietiesEnvironmentStageList = [];
              data.growthModelStageList.forEach((a) => {
                let varietiesEnvironmentStageDataList = [];
                a.growthModelStageDataList.forEach((b) => {
                  let src = {
                    dataTypeId: b.dataTypeId,
                    dataTypeName: b.dataTypeName,
                    lowerValue: b.lowerValue,
                    upperValue: b.upperValue
                  };
                  varietiesEnvironmentStageDataList.push(src);
                });
                let srca = {
                  growthPhaseId: a.growthPhaseId,
                  growthPhaseName: a.growthPhaseName,
                  varietiesEnvironmentStageDataList:
                    varietiesEnvironmentStageDataList
                };
                varietiesEnvironmentStageList.push(srca);
              });
              this.$set(
                this.formDataM,
                "varietiesEnvironmentStageList",
                varietiesEnvironmentStageList
              );
              console.log(this.formDataM);
            } else {
              this.formDataM = {
                batchCodeNo: "",
                growthModelId: "",
                varietiesEnvironmentStageList: [
                  {
                    growthPhaseId: "",
                    growthPhaseName: "",
                    varietiesEnvironmentStageDataList: [
                      {
                        dataTypeId: "",
                        dataTypeName: "",
                        upperValue: "",
                        lowerValue: ""
                      }
                    ]
                  }
                ]
              };
            }
          } else {
            this.$message.error(res.msg);
          }
        });
    },
    // 查询该品种的生长周期数（根据种养类型查询）
    queryEditGrowthByvariety() {
      configurationApi
        .queryByCondition({ plantingTypeId: this.plantingTypeId })
        .then((res) => {
          if (res.code === 1) {
            let data = res.data || [];
            this.growthPhaseIdList = data;
          } else {
            this.$message.error(res.msg);
          }
        });
    },
    // 给数据添加dataTypeName
    changeData(data, inddexA, index) {
      let dataTypeIndex = this.dataTypeList.findIndex(
        (a) => a.dataTypeId === data
      );
      if (dataTypeIndex !== -1) {
        this.formDataM.varietiesEnvironmentStageList[index][
          "varietiesEnvironmentStageDataList"
        ][inddexA]["dataTypeName"] =
          this.dataTypeList[dataTypeIndex]["dataTypeName"];
      }
    },
    // 添加某个生长周期的数据配置
    addModel(index, indexA) {
      let src = {
        dataTypeId: "",
        upperValue: "",
        dataTypeName: "",
        lowerValue: ""
      };
      this.$set(
        this.formDataM.varietiesEnvironmentStageList[index][
          "varietiesEnvironmentStageDataList"
        ],
        indexA + 1,
        src
      );
    },
    // 删除某个生长周期的数据配置
    delModel(index, indexA) {
      this.formDataM.varietiesEnvironmentStageList[index][
        "varietiesEnvironmentStageDataList"
      ].splice(indexA, 1);
    },
    close() {
      this.$emit("closeDialog");
    }
  }
};
</script>

<style scoped lang="scss">
.btns-box {
  display: flex;
  align-items: center;
  padding: 5px;
  > div {
    padding: 0 10px;
    display: flex;
    align-items: center;
    cursor: pointer;
  }
}
.input-label {
  text-align: right;
  font-size: 16px;
}
.submit-box {
  width: 100%;
  padding: 0 20px;
  text-align: right;
  .submit {
    background-color: rgba(0, 110, 145, 1);
  }
}
::v-deep .el-dialog {
  overflow-y: hidden;
}
::v-deep .el-dialog__body {
  overflow-y: scroll;
  max-height:600px;
}
::v-deep .el-form .el-form-item__label {
  color: #333333 !important;
}
::v-deep .el-input__inner {
  background: rgba(255, 255, 255, 0) !important;
  color: #333333 !important;
}
::v-deep .el-form-item {
  display: flex;
}
::v-deep .el-form-item__content {
  width: 100%;
}
::v-deep .el-form-item {
  margin: 0;
}
::v-deep .el-form .el-form-item__label {
  min-width: 70px;
}
.growth-model {
  width: 100%;
  display: flex;
  border-top: 1px dashed #b8b8b8;
  padding: 10px;
  .growth-model-info {
    width: 100%;
  }
}
.input-hang {
  display: flex;
  align-items: center;
  padding: 10px 0;

  > div {
    display: flex;
    align-items: center;
  }
}
::v-deep .el-form .el-form-item__label{
  min-width: 100px;
}
</style>
